package com.uam.core.business;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mapbox.geojson.Point;
import com.mapbox.turf.TurfConstants;
import com.mapbox.turf.TurfMeasurement;
import com.uam.core.business.help.CoordUtil;
import com.uam.core.business.mode.UamDataModelV2;
import com.uam.core.cache.PointCacheConfig;
import com.uam.core.config.UAMConfig;
import com.uam.core.dao.mysql.PolygonV1Dao;
import com.uam.core.dao.mysql.TaskDao;
import com.uam.core.entity.PointInfoData;
import com.uam.core.entity.constant.RedisConstants;
import com.uam.core.entity.model.AircraftModel;
import com.uam.core.entity.model.PolygonV1;
import com.uam.core.entity.model.RedisAltitudeInfo;
import com.uam.core.entity.model.TaskModel;
import com.uam.core.entity.uitls.SpatialUtil;
import com.uam.core.entity.uitls.ZipUtil;
import com.uam.core.service.RouteService;
import com.uam.core.tool.DateUtils;
import com.uam.core.tool.GetOldPointTool;
import lombok.extern.slf4j.Slf4j;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.Polygon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 更新数据库操作
 *
 * @author Administrator
 */
@Component
@Slf4j
public class OperationDbBusiness {
    @Autowired
    RedisTemplate<String,Object> redisTemplate;


    @Autowired
    private RouteService routeService;

    @Resource
    private PolygonV1Dao polygonV1Dao;

    @Resource
    private TaskDao taskDao;

    @Autowired
    private PointCacheConfig pointCacheConfig;

    /**
     * 轨迹点信息入库
     *
     * @param track            轨迹点
     * @param aircraftModel    飞行器信息
     * @param taskModel        任务信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void dbInfo(
                       JSONArray track,
                       AircraftModel aircraftModel,
                       TaskModel taskModel,
                       JSONObject route

    ) {
        double min_altitude = route.getDoubleValue("min_altitude");
        double max_altitude = route.getDoubleValue("max_altitude");
        double startAltitude = route.getDoubleValue("startAltitude");
        double endAltitude = route.getDoubleValue("endAltitude");

        RedisAltitudeInfo redisAltitudeInfo = new  RedisAltitudeInfo(min_altitude, max_altitude, startAltitude, endAltitude, taskModel, aircraftModel);
        setUpdataDb(track, redisAltitudeInfo);
        this.redisTemplate.opsForValue().set(RedisConstants.TASK_MODEL_INFO+taskModel.getId(),redisAltitudeInfo,1440, TimeUnit.MINUTES);
    }

    public void setUpdataDb(JSONArray track,  RedisAltitudeInfo redisAltitudeInfo ){
        List<PointInfoData> data1=new ArrayList();
        TaskModel taskModel=redisAltitudeInfo.getTaskModel();

        AircraftModel aircraftModel=redisAltitudeInfo.getAircraftModel();
        routeService.persistence(redisAltitudeInfo.getMin_altitude(),
                redisAltitudeInfo.getMax_altitude(),
                redisAltitudeInfo.getTaskModel(),
                aircraftModel,track.size() ,
                track, redisAltitudeInfo.getStartAltitude(),
                redisAltitudeInfo.getEndAltitude(),data1,
                true);
        try {
            double sum = 0.0;
            int row = data1.size();
            for (int i = 0; i < row; i++) {
                PointInfoData trackPointInfo = data1.get(i);
                sum=sum+trackPointInfo.getLast_position_distance();
            }
            double cost=(sum/(aircraftModel.getSpeed()*1000/3600))/60;
            long endTime=data1.get(row-1).getTime();
            Timestamp timestamp=new Timestamp(endTime);
            this.taskDao.updateTaskSu4(taskModel.getId(), sum, cost, timestamp,JSONArray.toJSONString(GetOldPointTool.getPoints(data1)));

        } catch (Exception e) {
            log.info("执行buffer错误：", e);
        }
        setRedisTrack(data1,aircraftModel,taskModel.getId());
        String points=  ZipUtil.compressBase64(JSONArray.toJSONString(track));
        redisTemplate.opsForValue().set(RedisConstants.ROUTE_POINTS+taskModel.getId(),points,1440, TimeUnit.MINUTES);
    }

    public List<Map<String, Object>> setUpdataDbCheck(JSONArray track,  RedisAltitudeInfo redisAltitudeInfo ){
        List<Map<String, Object>> dataMap=new ArrayList();
        AircraftModel aircraftModel=redisAltitudeInfo.getAircraftModel();
        routeService.persistenceCheck(redisAltitudeInfo.getMin_altitude(),
                redisAltitudeInfo.getMax_altitude(),
                redisAltitudeInfo.getTaskModel(),
                aircraftModel,track.size() ,
                track, redisAltitudeInfo.getStartAltitude(),
                redisAltitudeInfo.getEndAltitude(),dataMap);
        return dataMap;
    }

   public void setRedisTrack(List<PointInfoData> data1,AircraftModel aircraftModel, Integer taskId){
       int row=data1.size();
       Map<String,PointInfoData> tempArrMap = new LinkedHashMap<>();
       for(int i=0;i<row;i++){
           PointInfoData jsonArray0=data1.get(i);
           jsonArray0.setTaskId(taskId);
           jsonArray0.setSafeDistance(aircraftModel.getSafeDistance());
           jsonArray0.setSpeed(aircraftModel.getSpeed());
           jsonArray0.setBuffer(aircraftModel.getSafeDistance());
           jsonArray0.setFlightInterval(aircraftModel.getFlightInterval());
           tempArrMap.put(DateUtils.format(jsonArray0.getTime()),jsonArray0);
       }
       pointCacheConfig.add(taskId,tempArrMap);
   }

    public static void main(String[] args) {
        String data="H4sIAAAAAAAAAH3PQQrDQAxD0QsNITOpLfssIfe/RhMoQhS1XgnzN+8851xb9+wjx6ptxdwbY9/2\\r\\ncV5jYs3AQuz3XYNt96d91r+2mu3h2qkt2IZrD22DLVwb2h5s27XQlra0tpYWtKWzpdpAWzpbqg20\\r\\npbOl2kBbOluqDbTB2VJtSRucDWpL2uBsUFvSBmeD2pI2OBvUlrSVs0FtQVs5W6ktaCtnK7UFbeVs\\r\\npbagrZyt1Ba0tbOV2Ar383fa06Zrvb7KytdTXm+5UgYfHgQAAA==";
        System.out.println(ZipUtil.uncompressBase64(data));
    }
}
